import { defineStore } from 'pinia'
import { auth } from '@/api/all'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null,
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.user?.role === 'admin',
    isNurse: (state) => state.user?.role === 'nurse',
  },

  actions: {
    async login(username, password) {
      try {
        const response = await auth.login({ username, password })
        console.log('Login response:', response)

        const { token, user } = response.data
        console.log('Extracted data:', { token, user })

        if (token && user) {
          this.token = token
          localStorage.setItem('token', token)

          this.user = user
          console.log('Stored user:', this.user)

          return { token, user }
        } else {
          throw new Error('Invalid response format')
        }
      } catch (error) {
        console.error('Login error:', error)
        ElMessage.error(error.response?.data?.message || '登录失败')
        throw error
      }
    },

    async register(userData) {
      try {
        const response = await auth.register(userData)
        ElMessage.success('注册成功')
        return response
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '注册失败')
        throw error
      }
    },

    logout() {
      this.user = null
      this.token = null
      localStorage.removeItem('token')
    },

    updateUserAvatar(avatarUrl) {
      console.log('Store: 更新用户头像', avatarUrl)
      if (this.user) {
        this.user = {
          ...this.user,
          avatar_url: avatarUrl,
        }
        console.log('Store: 更新后的用户信息', this.user)
      }
    },

    async fetchUserProfile() {
      try {
        if (this.token) {
          console.log('获取用户信息...')
          const response = await auth.getUserInfo()
          console.log('用户信息响应:', response)
          this.user = response.data
          return response.data
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        if (error.response?.status === 401) {
          this.logout()
        }
        throw error
      }
    },

    async initializeAuth() {
      if (this.token && !this.user) {
        try {
          await this.fetchUserProfile()
        } catch (error) {
          console.error('初始化认证失败:', error)
          this.logout()
        }
      }
    },
  },
})
